package cn.wangfeixiong.filter;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

@Slf4j
public class CachingHttpServletRequest extends HttpServletRequestWrapper {
    private final byte[] body;

    public CachingHttpServletRequest(HttpServletRequest request) throws IOException {
        super(request);
        // 使用 try-with-resources 自动关闭资源
        try (BufferedReader reader = new BufferedReader(
            new InputStreamReader(
                request.getInputStream(),
                getCharset(request)
            )
        )) {
            StringBuilder stringBuilder = new StringBuilder();
            char[] buffer = new char[8192];
            int bytesRead;
            // 使用缓冲区读取提高性能
            while ((bytesRead = reader.read(buffer)) != -1) {
                stringBuilder.append(buffer, 0, bytesRead);
            }
            // 使用正确的编码转换为字节数组
            body = stringBuilder.toString().getBytes(getCharset(request));
        } catch (IOException e) {
            // 记录完整异常信息
            log.error("Failed to read request body", e);
            // 重新抛出异常保持方法签名
            throw e;
        }
    }

    // 提取字符集获取逻辑为单独方法
    private String getCharset(HttpServletRequest request) {
        String charset = request.getCharacterEncoding();
        return charset != null ? charset : StandardCharsets.UTF_8.name();
    }

    // 添加获取缓存体的方法
    public String getBody() {
        if (body == null || body.length == 0) {
            return null;
        }
        return new String(body); // 返回副本保护原始数据
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body);
        return new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return byteArrayInputStream.available() == 0;
            }

            @Override
            public boolean isReady() {
                return true;
            }

            @Override
            public void setReadListener(ReadListener readListener) {
                throw new UnsupportedOperationException();
            }

            @Override
            public int read() throws IOException {
                return byteArrayInputStream.read();
            }
        };
    }
}